
const fs = require('fs');
const Sequelize = require('sequelize');
const { DATABASE } = require('../config');

const sequelize = new Sequelize(
  DATABASE.database,
  DATABASE.user,
  DATABASE.password,
  DATABASE.options
);

const db = {};

const fileList = fs.readdirSync(__dirname);
fileList.forEach(fileName => {
  // 读取文件并传入sequelize
  if (fileName !== 'index.js') {
    const model = require(`./${fileName}`)(sequelize, Sequelize.DataTypes);
    // 查
    model.find = params => model.findOne({ raw: true, where: params });
    // 增
    model.createData = data => model.create(data);
    db[fileName.split('.')[0]] = model;
  }
})

db.sequelize = sequelize;

module.exports = db